package 
{
	import common.IApp;
	import common.IAppBuilder;
	
	import flash.display.Sprite;
	import flash.events.Event;
	
	import pong.app.IPongAppSkinFactory;
	import pong.app.builders.PongAppBuilder;
	import pong.app.factories.PongAppSkinFactory;
	
	/**
	 * ...
	 * @author Luke Van In
	 */
	[SWF(width="600", height="420", frameRate="60", backgroundColor="#000000")]
	[Frame(factoryClass="PongFuLoader")]
	public class PongFuMain extends Sprite 
	{
		
		private var _app:IApp;
		
		
		/**
		 * Constructor
		 */
		public function PongFuMain():void 
		{
			if (this.stage != null) 
			{
				// movieclip is on stage, initialise the application
				this.initialise();
			}
			else 
			{
				// movieclip is still initialising, wait before loading the application
				this.addEventListener(Event.ADDED_TO_STAGE, this.onAddedToStage);
			}
		}
		
		
		/**
		 * Movieclip added to the stage
		 * 
		 * @param	e
		 */
		private function onAddedToStage(e:Event):void
		{
			this.removeEventListener(Event.ADDED_TO_STAGE, this.onAddedToStage);
			
			this.initialise();
		}
		
		
		
		/**
		 * Creates an application instance if one does not already exist
		 * 
		 * @throws	Error	Cannot instance more than one app at a time
		 */
		private function initialise():void 
		{
			if (this._app != null)
				throw new Error("Application already initialised");
				
			var skinFactory:IPongAppSkinFactory = new PongAppSkinFactory();
			
			var builder:IAppBuilder = new PongAppBuilder(skinFactory, this);
			
			this._app = builder.buildApp();
			
			this._app.start();
		}
		
	}
	
}